import sys
import time
import fcntl

class flock(object):

    def __init__(self, name):
        self.fobj = open(name, 'w')
        self.fd = self.fobj.fileno()

    def lock(self):
        try:
            fcntl.lockf(self.fd, fcntl.LOCK_EX | fcntl.LOCK_NB)  # 给文件加锁，使用了fcntl.LOCK_NB
            print ('给文件加锁，稍等 ... ...')
            time.sleep(20)
            return True
        except:
            print ('文件加锁，无法执行，请稍后运行。')
            return False

    def unlock(self):
        self.fobj.close()
        print ('已解锁')
